//
//  OneToOneChatViewController.m
//  GolfFriend
//
//  Created by vescky on 13-11-24.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "OneToOneChatViewController.h"
#import "ChatCell.h"
#import "SVProgressHUD.h"
#import "AppsEngine.h"
#import "ChatDAO.h"
#import "UserSession.h"
#import "JSON.h"

#import "DateUtility.h"
#import "CommonUtility.h"
#import "DateUtility.h"
#import "AppDelegate.h"
#import "ContactBook.h"

#import "ImageUploader.h"
#import "PersonalInfoViewController.h"

#import "AppDelegate.h"

#define IMG_FACE_PREFIX @"["
#define IMG_FACE_SUFFIX @"]"

#define FACE_CELL_SIZE CGSizeMake(32, 32)
#define FACE_CELL_COLUMN 7
#define FACE_CELL_ROW 3

@interface OneToOneChatViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate> {
    NSMutableArray *facesArray,*chatContentArray;
    UIPageViewController *pageController;
    ChatCell *sampleCell;
    int totalPages;
    bool firstTimeToSend;
    UIImagePickerController *photoPicker;
    UIActionSheet *photoActionSheet;
    
    NSMutableDictionary *userInfo;
}

@end

@implementation OneToOneChatViewController
@synthesize userId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initView];
    [self initData];
    [super customBackButton];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [APP_DELEGATE closeMesageStatusBarAlert];
//    [self performSelector:@selector(scrollToChatListEnd) withObject:nil afterDelay:0.1];
    [self performSelectorOnMainThread:@selector(scrollToChatListEnd)  withObject:nil waitUntilDone:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Private
- (void)initView {
    facesArray = [[NSMutableArray alloc] init];
    chatContentArray = [[NSMutableArray alloc] init];
    sampleCell = [[ChatCell alloc] init];
    
    //给srcollview添加手势
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [scFaces addGestureRecognizer:swipeRight];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    UISwipeGestureRecognizer *swipeleft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [scFaces addGestureRecognizer:swipeleft];
    swipeleft.direction = UISwipeGestureRecognizerDirectionLeft;
    
    //给table添加单击事件
    UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [tbChatList addGestureRecognizer:tapOnce];
    tapOnce.numberOfTapsRequired = 1;
    
    viewFaces.hidden = YES;
    
    //定制自己的风格的  UIBarButtonItem
    UIButton* publishButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 30, 26)];//
    [publishButton setBackgroundImage:[UIImage imageNamed:@"btn_personal_info.png"] forState:UIControlStateNormal];
//    [publishButton setImage:[UIImage imageNamed:@"chat_06.png"] forState:UIControlStateHighlighted];
    [publishButton addTarget:self action:@selector(gotoUserInfoView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
    
    //监听键盘高度的变换
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 键盘高度变化通知，ios5.0新增的
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
#endif
}

- (void)initData {
    if (userId && userId.length <= 0) {
        return;
    }
    
    firstTimeToSend = YES;
    
    userInfo = [[ContactBook shareContactBook] getUserInfo:userId];
    if (isValueSet([userInfo objectForKey:@"nickName"])) {
        self.title = [userInfo objectForKey:@"nickName"];
    }
    else {
        self.title = userId;
    }
    
    NSString *avatarLink = [userInfo objectForKey:@"avatar"];
    
    ChatDAO *cDao = [ChatDAO  shareChatDAO];
    NSMutableArray *arr = [cDao getMessagesByUserId:userId range:NSMakeRange(0, 10)];
    arr = [self resortMessagesByTimeDesc:arr];
    [cDao readUserMessage:userId];//已读取过此用户的消息
    for (int i = 0; i < [arr count]; i++) {
        NSDictionary *dict = [arr objectAtIndex:i];
        NSMutableDictionary *cDict = [[NSMutableDictionary alloc] init];//content,isSelf,type
        [cDict setObject:[dict objectForKey:@"content"] forKey:@"content"];
        [cDict setObject:[dict objectForKey:@"msgType"] forKey:@"type"];
        if ([[dict objectForKey:@"fromId"] isEqualToString:[[UserSession shareUserSession] getUserId]]) {
            [cDict setObject:@1 forKey:@"isSelf"];
        }
        else {
            [cDict setObject:@0 forKey:@"isSelf"];
        }
        if (isValueSet(avatarLink)) {
            [cDict setObject:avatarLink forKey:@"avatar"];
        }
        if (isValueSet(cDict)) {
            [chatContentArray addObject:cDict];
        }
    }
}

- (void)scrollToChatListEnd {
    if ([chatContentArray count] < 1) {
        return;
    }
    [tbChatList scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:[chatContentArray count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (bool)isMessage:(NSDictionary*)msg1 laterThen:(NSDictionary*)msg2 {
    NSString *timeString1 = [msg1 objectForKey:@"time"];
    NSString *timeString2 = [msg2 objectForKey:@"time"];
    NSDate *date1 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", timeString1);
    NSDate *date2 = getDateFromString(@"yyyy-MM-dd HH:mm:ss", timeString2);
    
    if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
        return YES;
    }
    
    return NO;
}

- (NSMutableArray*)resortMessagesByTimeDesc:(NSArray*)mArr {
    if (!isValueSet(mArr)) {
        return nil;
    }
    //按时间排序，从晚到早
    NSArray *sortedArr = [mArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if ([self isMessage:obj2 laterThen:obj1]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        else {
            return (NSComparisonResult)NSOrderedDescending;
        }
    }];
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}


- (void)loadFaces {
    NSString *imgBundlePath = [NSString stringWithFormat:@"%@/faces.bundle",[[NSBundle mainBundle] bundlePath]];
	NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *facesList = [fm contentsOfDirectoryAtPath:imgBundlePath error:nil];
    for (int i = 0; i < [facesList count]; i++) {
        NSString *imgName = [facesList objectAtIndex:i];
        NSString *imgPath = [imgBundlePath stringByAppendingPathComponent:imgName];
        NSString *imgIden = [NSString stringWithFormat:@"%@%@%@",IMG_FACE_PREFIX,[imgName stringByDeletingPathExtension],IMG_FACE_SUFFIX];
        UIImage *image = [UIImage imageWithContentsOfFile:imgPath];
        if (imgIden && image) {
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:imgIden,@"value",image,@"image", nil];
            [facesArray addObject:dict];
        }
    }
    
    totalPages = [facesArray count] / (FACE_CELL_COLUMN * FACE_CELL_ROW);
    float margin = 11;
    float rowHeight = FACE_CELL_SIZE.height + margin;
    float rowWidth = rowHeight;
    float originX = 0,originY = 0;
    for (int i = 0; i < [facesArray count]; i++) {
        if (i % 7 == 0) {
            int cPage = i / (FACE_CELL_COLUMN * FACE_CELL_ROW);
            originX = cPage * self.view.frame.size.width + 2;
            originY = (i / 7 - cPage * FACE_CELL_ROW) * rowHeight;
        }
        
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(originX + margin, originY + margin, FACE_CELL_SIZE.width, FACE_CELL_SIZE.height)];
        [imgv setImage:[[facesArray objectAtIndex:i] objectForKey:@"image"]];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(originX, originY, rowWidth, rowHeight)];
        [btn setBackgroundColor:[UIColor clearColor]];
        [btn addTarget:self action:@selector(faceDidSelect:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 200 + i;
        [scFaces addSubview:imgv];
        [scFaces addSubview:btn];
        NSLog(@">>> this cell frame:%@",btn);
        originX = originX + rowWidth;
    }
    
    [scFaces setContentSize:CGSizeMake(scFaces.frame.size.width * totalPages, scFaces.frame.size.height)];
    pageControll.numberOfPages = totalPages;
    pageControll.currentPage = 0;
}


- (void)changeToolBarPosition:(float)_originY {
    __block CGRect tRect = viewTool.frame;
    tRect.origin.y = _originY;
    
    [viewTool setFrame:tRect];
    
    CGRect sRect = viewSelect.frame;
    sRect.origin.y = _originY - sRect.size.height - 5;
    [viewSelect setFrame:sRect];
    
    CGRect tbRect = tbChatList.frame;
    tbRect.size.height = _originY;
    [tbChatList setFrame:tbRect];
    if ([chatContentArray count] >= 1) {
        [tbChatList scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[chatContentArray count]-1 inSection:0]  atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}

- (void)setFaceViewHidden:(BOOL)_isHidden {
    if (_isHidden) {
        //忽略已经隐藏的，只处理已隐藏的情况
//        if (!viewFaces.hidden) {
            [viewFaces removeFromSuperview];
            [self changeToolBarPosition:self.view.frame.size.height - viewTool.frame.size.height];
            viewFaces.hidden = _isHidden;
//        }
    }
    else {
        //忽略已显示的，只处理已隐藏的情况
//        if (viewFaces.hidden) {
            viewFaces.hidden = _isHidden;
            CGRect fRect = viewFaces.frame;
            fRect.origin.y = self.view.frame.size.height - fRect.size.height;
            [viewFaces setFrame:fRect];
            [self changeToolBarPosition:fRect.origin.y - viewTool.frame.size.height];
            [self.view addSubview:viewFaces];
            if (!facesArray || [facesArray count] < 1) {
                [self loadFaces];
            }
//        }
    }
    
}

- (NSString*)getChatImageSaveName {
    NSString *dateString = getStringFromDate(@"yyyyMMddHHmmss", [NSDate date]);
    NSString *fromId = [[UserSession shareUserSession] getUserId];
    NSString *toId = userId;
    if (!toId) {
        toId = @"1";
    }
    NSString *sNo = getRandomStrings(5);
    NSString *sName = [NSString stringWithFormat:@"singleChat_%@_%@_%@_%@.png",dateString,fromId,toId,sNo];
    return sName;
}

- (void)sendMessage:(NSMutableDictionary*)_dict {
    [chatContentArray addObject:_dict];
    [self reloadChatList];
    
    if (!_dict || [_dict count] <= 0 || ![_dict objectForKey:@"type"]) {
        return;
    }
    
    NSString *fromId = [[UserSession shareUserSession] getUserId];
    NSString *toId = userId;
    NSString *msgType = @"1";
    NSString *content = [_dict objectForKey:@"content"];
//    NSMutableDictionary *sourceLink = [[NSMutableDictionary alloc] init];
    if (![[_dict objectForKey:@"type"] isEqualToString:Message_Type_Txt]) {
        msgType = @"2";
        content = [NSString stringWithFormat:@"%@/%@",Qiniu_Backet_Domain,[[_dict objectForKey:@"content"] lastPathComponent]];
//        [self uploadPhoto:[_dict objectForKey:@"content"]];
        [APP_DELEGATE uploadImageWithArray:[[NSArray alloc] initWithObjects:[_dict objectForKey:@"content"], nil] saveNameList:[[NSArray alloc] initWithObjects:[[_dict objectForKey:@"content"] lastPathComponent], nil] submitToSinaPaarms:nil];
    }
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:fromId,@"fromId",toId,@"toId",@"0",@"isGroupChat",content,@"content",msgType,@"msgType",nil];
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfSendMessage" param:dict onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"聊天消息发送成功!");
            NSMutableDictionary *msgDict = [[NSMutableDictionary alloc] initWithDictionary:jsonResponse];
            if ([[msgDict objectForKey:@"msgType"] integerValue] == 2) {
                //图片
                NSString *qiniuImageLink = [msgDict objectForKey:@"content"];
                NSString *localPath = [getCachePath() stringByAppendingString:[qiniuImageLink lastPathComponent]];
                NSFileManager *fm = [NSFileManager defaultManager];
                if ([fm fileExistsAtPath:localPath isDirectory:NO]) {
                    [msgDict setObject:localPath forKey:@"content"];
                }
                [[ChatDAO shareChatDAO] saveMessage:msgDict];
            }
        }
        else {
            NSLog(@"-------------  聊天消息发送失败!\n reason:%@",[jsonResponse objectForKey:@"reason"]);
        }
    } onError:^(NSError *error) {
        NSLog(@"------------- 聊天,无法连接网络!\nreason:%@",error);
    } method:@"GET"];
    
    long lastestId = [[ChatDAO shareChatDAO] getLatestMsgId] + 1;
    [dict setObject:getStringFromDate(@"yyyy-MM-dd HH:mm:ss", [NSDate date]) forKey:@"time"];
    [dict setObject:[NSString stringWithFormat:@"%ld",lastestId] forKey:@"id"];
    [[ChatDAO shareChatDAO] saveMessage:dict];
    
    if (firstTimeToSend) {
        [[UserSession shareUserSession] saveChatWindow:toId];
        firstTimeToSend = NO;
    }
}

- (void)reloadChatList {
    [self textViewDidChange:tvContent];
    [tbChatList reloadData];
    if ([chatContentArray count] >= 1) {
        [tbChatList scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[chatContentArray count]-1 inSection:0]  atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}


- (void)uploadPhoto:(NSString*)photoPath {

//    __block NSString *pPath = photoPath;
//    //上传图片
//    dispatch_queue_t queue = dispatch_queue_create("OneToOneChat", NULL);
//    dispatch_async(queue, ^{
//            //这是名媛荟沙盒的文件
//        if ([pPath stringByMatching:@"GF-Document:"]) {
//            pPath = [photoPath stringByReplacingOccurrencesOfString:@"GF-Document:" withString:@""];
//        }
//        
////        if ([[ImageUploader shareImageUploader] uploadImage:pPath asName:[pPath lastPathComponent]]) {
////            //上传图片成功
////            NSLog(@"-----------OneToOneChatViewController-uploadPhotos \n photo upload success \n local:%@ \n---------------",pPath);
////        }
//        
//        [APP_DELEGATE uploadImageWithArray:[[NSArray alloc] initWithObjects:pPath, nil] saveNameList:[[NSArray alloc] initWithObjects:[pPath lastPathComponent], nil] submitToSinaPaarms:nil];
//        
//    });
}

- (void)gotoUserInfoView {
    PersonalInfoViewController *pVc = [[PersonalInfoViewController alloc] init];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:userInfo];
    [dict setObject:[userInfo objectForKey:@"uId"] forKey:@"userId"];
    pVc.userInfo = dict;
    [self.navigationController pushViewController:pVc animated:YES];
}


#pragma mark - 处理手势
- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer
{
    NSLog(@"Swipe");
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        //向右,向后翻页
        if (pageControll.currentPage < totalPages - 1) {
            pageControll.currentPage++;
            [scFaces setContentOffset:CGPointMake(pageControll.currentPage * self.view.frame.size.width, scFaces.frame.origin.y) animated:YES];
        }
    }
    else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        //向左,向前翻页
        if (pageControll.currentPage > 0) {
            pageControll.currentPage--;
            [scFaces setContentOffset:CGPointMake(pageControll.currentPage * self.view.frame.size.width, scFaces.frame.origin.y) animated:YES];
        }
    }
}

-(void)handleGesture:(UITapGestureRecognizer*)tapRecognizer {
    [tvContent resignFirstResponder];
    [self setFaceViewHidden:YES];
    [viewSelect setHidden:YES];
}

#pragma mark - Button Action
- (IBAction)faceDidSelect:(id)sender {
    UIButton *btn = (UIButton*)sender;
    NSLog(@"selected No.%d face",btn.tag);
    NSDictionary *dict = [facesArray objectAtIndex:btn.tag - 200];
    if (dict) {
       tvContent.text = [tvContent.text stringByAppendingString:[dict objectForKey:@"value"]];
    }
    
}

- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 101) {
        //更多菜单
        [viewSelect setHidden:!viewSelect.hidden];
    }
    else if (btn.tag == 102) {
        if (tvContent.text.length < 1) {
            [SVProgressHUD showErrorWithStatus:@"不能发送空内容"];
            return;
        }
        //发送
        NSLog(@"发送");
        [viewSelect setHidden:YES];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:tvContent.text,@"content",
                                     Message_Type_Txt,@"type",@1,@"isSelf", nil];
        [self sendMessage:dict];
        tvContent.text = @"";
        
        [self reloadChatList];
    }
    else if (btn.tag == 103) {
        //选择表情
        [viewSelect setHidden:YES];
        [self setFaceViewHidden:NO];
        [tvContent resignFirstResponder];
    }
    else if (btn.tag == 104) {
        //选择图片
        [viewSelect setHidden:YES];
        [self setFaceViewHidden:YES];
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"用相机拍一张",@"从相册选一张", nil];
        photoActionSheet = actionSheet;
        photoActionSheet.delegate = self;
        [photoActionSheet showInView:self.view];
    }
    else if (btn.tag == 105) {
        //个人资料
        [viewSelect setHidden:YES];
        [self setFaceViewHidden:YES];
    }

}

#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    
    NSDictionary *userInfo = [notification userInfo];
    
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
//    [self autoMovekeyBoard:keyboardRect.size.height];
    [self changeToolBarPosition:self.view.frame.size.height - keyboardRect.size.height - viewTool.frame.size.height];
}


- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    
    if (viewFaces.hidden) {
        [self changeToolBarPosition:self.view.frame.size.height - viewTool.frame.size.height];
    }
    else {
        [self setFaceViewHidden:NO];
    }

}



#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [chatContentArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"ChatCell";
    ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        //        cell = [[[NSBundle mainBundle] loadNibNamed:@"VKCollectionViewCell" owner:self options:nil] objectAtIndex:0];
        cell = [[ChatCell alloc] init];
    }
    
    [cell setDataInfo:[chatContentArray objectAtIndex:indexPath.row]];
    [cell setTag:300+indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    float cellHeight = [sampleCell getCellFrameHeight:[chatContentArray objectAtIndex:indexPath.row]];
    NSLog(@"--- cellHeight:%f",cellHeight);
    if (cellHeight <= 0) {
        cellHeight = 40;
    }
    return cellHeight;
}


#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
    [viewSelect setHidden:YES];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
}

- (void)textViewDidChange:(UITextView *)textView {
    CGSize size = [textView.text sizeWithFont:textView.font constrainedToSize:CGSizeMake(210, 3000) lineBreakMode:2];
    float tvHeight = 40 * (size.height / 40);
    CGRect tvRect = tvContent.frame;
    if (tvHeight <= 40) {
        tvHeight = 40;
    }
    else if (tvHeight > 40 && tvHeight <= 60) {
        tvHeight = 60;
    }
    else {
        tvHeight = 80;
    }
    
    if (tvContent.frame.size.height == tvHeight) {
        //无变化，可以忽略
        return;
    }
    
    tvRect.size.height = tvHeight;
    [tvContent setFrame:tvRect];
    
    CGRect toolRect = viewTool.frame;
    toolRect.origin.y = toolRect.origin.y - (tvHeight - toolRect.size.height) - 10;
    toolRect.size.height = tvHeight + 10;
    [viewTool setFrame:toolRect];
}

#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;  //是否可编辑
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            photoPicker = picker;
            [self presentModalViewController:photoPicker animated:YES];
        }
        else{
            //如果没有提示用户
            [SVProgressHUD showErrorWithStatus:@"您的设备不支持拍照!"];
        }
    }
    else {
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        photoPicker = picker;
        [self presentModalViewController:photoPicker animated:YES];
    }
    
}


#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
//拍摄完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//[self saveAndResizeImage:image asName:@"tmp.png"]
        NSString *savePath = [NSString stringWithFormat:@"GF-Document:%@",saveAndResizeImage(image, [self getChatImageSaveName],640)];
        __block NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:savePath,@"content",//UIImage
                              Message_Type_Pic,@"type",@1,@"isSelf",nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            //tb reload
            [self sendMessage:dict];
        });
    });
    
    //图片存入相册
    [self dismissModalViewControllerAnimated:YES];
}

//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}


@end




